package com.scalar.chiptrack.adaptor.telefunken;

import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.adaptor.dao.AdaptorRunInfo;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.utils.DateUtil;
import com.scalar.chiptrack.users.VendorAdaptor;
import com.scalar.chiptrack.users.dao.AdaptorSetUpDAO;
import com.scalar.ScalarException;

import com.enterprisedt.net.ftp.FTPClient;
import com.enterprisedt.net.ftp.FTPTransferType;
import com.enterprisedt.net.ftp.FTPConnectMode;

import HTTPClient.HTTPConnection;
import HTTPClient.HTTPResponse;
import HTTPClient.CookieModule;
import HTTPClient.NVPair;

import javax.mail.Message;
import java.io.IOException;
import java.io.FileOutputStream;

/**
 * Created by IntelliJ IDEA.
 * User: munugoti
 * Date: 10 Mar, 2010
 * Time: 12:10:02 PM
 */
public class TeleFunkenAdaptor extends JobHandler implements AdaptorConstants
{
    //http://foundry.telefunkensemi.com/fc_server/fc_check_pass.php3

    //private static final int PORT                       = 80;
    private static final String HOST                    = "foundry.telefunkensemi.com";
    private static final String POST_URI_LOGIN          = "/fc_server/fc_check_pass.php3";
    private static final int    PORT            = 21;
    private static final String FTP_HOST        = "ftp.telefunkensemi.com";
    private static final String POP3_HOST                = "mail.scalarsoft.com";
	
    public static final String FILE_NAME_WIP 	= "Telefunken";
    public static final String FILE_NAME_SHIP 	= "AKROS_SHIPPINGREPORT";
    public static final String SUBJECT_SHIP 	= "Telefunken Shipping Report";

	public static final String ADAPTOR_NAME     = "TELEFUNKEN_FAB";

    private String m_dataOutputDir      = null;
    private Logger m_adaptorLogger      = null;
    private String m_username           = null;   //UO5AB0SC
    private String m_password           = null;   //904mr2pk
    private int    m_adaptor_id     = -1;

    public TeleFunkenAdaptor() throws Exception
    {
        try
        {
            VendorAdaptor vendorAdaptor = AdaptorSetUpDAO.getVendorAdaptorDetailsByVendorNameAndLocation( VENDOR_NAME_TELEFUNKEN, LOCATION_TYPE_FAB );

            m_username = vendorAdaptor.getUserId().trim();
            m_password = vendorAdaptor.getPassWord().trim();
            m_dataOutputDir = vendorAdaptor.getOutPutDirectory().trim();

            if ( m_dataOutputDir != null )
            {
                if ( m_dataOutputDir.endsWith( "/" ) || m_dataOutputDir.endsWith( "\\" ) )
                {
                    m_dataOutputDir = m_dataOutputDir + m_username;
                }
                else
                {
                    m_dataOutputDir = m_dataOutputDir + "/" + m_username;
                }

                AdaptorUtils.makeAllAdaptorDirs( m_dataOutputDir );
                m_adaptorLogger  =  AdaptorUtils.getAdaptorLogger( m_dataOutputDir, VENDOR_NAME_TELEFUNKEN );
                AdaptorUtils.setLogger( m_adaptorLogger );
            }
        }
        catch ( Exception se )
        {
            log( "ERROR!! ERROR!! ERROR!! Exception while loading TELEFUNKEN Adaptor Username, Password details from database, Exception: " + se );
            throw new ScalarException( "Exception while loading TELEFUNKEN Adaptor Username, Password details from database" );
        }
    }

    public static void main( String[] args ) throws Exception
    {
        new TeleFunkenAdaptor().execute();
    }

    public void execute() throws Exception
    {
        m_adaptor_id = AdaptorRunInfo.saveAdaptorLastUpdatedStatus( CONSTANT_ADAPTOR, ADAPTOR_NAME, CONSTANT_SUCCESS, -1);
        //Print the header details
        AdaptorUtils.printHeader(VENDOR_NAME_TELEFUNKEN, CONSTANT_ADAPTOR);

        AdaptorUtils.removeOldFiles( m_dataOutputDir, m_adaptorLogger );

        /*HTTPConnection connection = login( HOST , PORT   );

        if ( connection != null )
        {
            BufferedInputStream bfReader = null;
            try
            {
                //For DownLoading WipStatus Report
                HTTPResponse rsp = requestWipStatusReport( connection );

                if( rsp != null )
                {
                    bfReader = new BufferedInputStream( rsp.getInputStream()  );
                    if( bfReader != null )
                    {
                        System.out.println( "\tDownloading the Wip Report..." );
                        log( "\tDownloading the Wip Report..." );
                        AdaptorUtils.saveAsBinaryFile( bfReader, m_dataOutputDir, FILE_NAME_WIP_STATUS , FILE_EXTN_HTML,true );

                        if ( m_adaptor_id > 0 )
                        {
                            AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , FILE_NAME_WIP_STATUS, FILE_EXTN_HTML, StringUtils.formatDateandTime(DateUtil.getFormattedTimeStamp() )) ;
                        }
                    }
                    else
                    {
                        log( "Could not save Wip and Orders Sheet from Buffer Reader" );
                        throw new ScalarException( "Could not save Wip and Orders Sheet from Buffer Reader" );
                    }
                }
                else
                {
                    log( "Could not create response object of Wip and Orders Sheet" );
                    throw new ScalarException( "Could not create response object of Wip and Orders Sheet" );
                }
                // Logging out from WEB SITE
                //logout( connection );
                 bfReader = null;
            }
            finally
            {
                 if ( bfReader != null )
                 {
                     bfReader.close();
                     bfReader = null;
                 }
            }

        }
        else
        {
            log( "Could not able to get the Connection to web site" );
            throw new ScalarException( "Could not able to get the Connection to web site" );
        } */

		FTPClient ftp = login( FTP_HOST, PORT, m_username, m_password );
		log( "Successfully logged in to " + FTP_HOST );
		System.out.println( "Successfully logged in to " + FTP_HOST );

         ftp.chdir("/to_ScalarSoft/WIPREPORT");
         //To Down DownLoad the File To Local System at Specepied path
         downloadWIPFiles( ftp );
         // Log out
         logout( ftp );
         log( "\nSuccessfully logged out from Telefunken Ftp Site" );
         System.out.println( "\nSuccessfully logged out from Telefunken FTP Site" );

         //Retrive All the Messages
          Message[] messages = AdaptorUtils.getAllPOP3InboxMessages( POP3_HOST, "akros@scalarsoft.com", "Ontrac20");
          // Step 4
          // Retrieve & Saves the latest message
          AdaptorUtils.readLatestMessage( m_adaptor_id, messages, SUBJECT_SHIP,  m_dataOutputDir, FILE_EXTN_CSV,null);
    }

	private FTPClient login( String host, int port, String username, String password ) throws Exception
    {
        FTPClient ftp = new FTPClient( host, port );
        ftp.login( username, password );
        ftp.debugResponses( false );
        ftp.setType( FTPTransferType.BINARY );
        // active does not allows me connect to ftp site even any proxy lies in path.
        ftp.setConnectMode( FTPConnectMode.PASV );
        return ftp;
    }

	private void downloadWIPFiles( FTPClient ftp ) throws Exception
   	{
	   String[] listings = ftp.dir();

       if ( ( listings == null ) || ( listings.length == 0 ) )
       {
           return;
       }
        byte[] buf = null;
        String tempFileName     = null;
        FileOutputStream fileOutputStream = null;
        System.out.println("\t\n Downloading the WIP file...... " );
        try
        {
            for ( int i = 0; i < listings.length; i++ )
            {
                if ( listings[i].startsWith( "WIP1015" ) )
                {                                                                                                     
                    if (tempFileName == null)
                    {
                        tempFileName = listings[i];
                    }
                    else
                    {
                        java.util.Date date1 = ftp.modtime(tempFileName);
                        java.util.Date date2 = ftp.modtime(listings[i]);

                        if( date1 != null && date2 != null)
                        {
                            if (date2.compareTo(date1) > 0 )
                            {
                                tempFileName = listings[i];
                            }
                        }
                    }
                }
            }
            if ( tempFileName != null )
            {
                log( "\ndownloading file " + tempFileName + " to " + m_dataOutputDir + " directory... " );
                if ( m_adaptor_id > 0 )
                {
                    AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , tempFileName.substring(0, tempFileName.indexOf(".") ), FILE_EXTN_TXT, StringUtils.formatDateToString(ftp.modtime(tempFileName), "MM/dd/yyyy HH:mm:ss" ) ) ;
                }
                buf = ftp.get( tempFileName );

                tempFileName = FILE_NAME_WIP + "_" + tempFileName.substring(0, tempFileName.indexOf(".") ) +  "." + FILE_EXTN_TXT;
                fileOutputStream = new FileOutputStream( m_dataOutputDir + "/" + tempFileName, false );
                fileOutputStream.write( buf );
                fileOutputStream.flush();
                tempFileName = null;
            }
        }
        catch ( Exception e )
        {
            log ("Exception while downloading......... " + e);
            logout( ftp );
            throw e;
        }

        finally
        {
            if ( fileOutputStream != null )
            {
                try
                {
                    fileOutputStream.flush();
                    fileOutputStream.close();
                }
                catch ( IOException ignore )
                {
                }
           }
       }
   }
   private void logout( FTPClient ftp ) throws Exception
    {
        if ( ftp == null )
        {
            return;
        }
        try
        {
            ftp.quit();
        }
        catch ( Exception ignore )
        {
            System.out.println( "Exception Occuered While Logging Out From TeleFunken FTP Site" + ignore );
            throw ignore;
        }
        ftp = null;
    }
    /**
     *
     * @param host
     * @param port
     * @return
     * @throws Exception
     */

    private HTTPConnection login( String host, int port ) throws Exception
    {
        byte[] data         = new byte[1024];

        HTTPConnection conn = new HTTPConnection(host, port );
        CookieModule.setCookiePolicyHandler( null );
        HTTPConnection.addDefaultModule( CookieModule.class, -1 );

        NVPair defaultHeaders[] = new NVPair[ 7 ];
        defaultHeaders[ 0 ] = new NVPair( "Accept", "image/gif, image/x-xbitmap, image/jpeg, application/x-ms-application, application/vnd.ms-xpsdocument, application/xaml+xml, application/x-ms-xbap, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, image/pjpeg, */*" );
        defaultHeaders[ 1 ] = new NVPair( "Accept-Language", "en-us" );
        defaultHeaders[ 2 ] = new NVPair( "Content-Type", "application/x-www-form-urlencoded" );
        defaultHeaders[ 3 ] = new NVPair( "Proxy-Connection", "Keep-Alive" );
        defaultHeaders[ 4 ] = new NVPair( "User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; InfoPath.2; .NET CLR 3.5.30729; .NET CLR 3.0.30729)" );
        defaultHeaders[ 5 ] = new NVPair( "Host", host );
        defaultHeaders[ 6 ] = new NVPair( "Authorization" , "Basic VU81QUIwU0M6OTA0bXIycGs=" );

        conn.setDefaultHeaders( defaultHeaders );

        HTTPResponse rsp = conn.Get( "/fc_server/" );

        /*while ( rsp.getInputStream().read( data ) != -1 )
        {
        	log( new String( data ) );
        }*/
        System.out.print( "Trying to Logging in......" );
        log( "Trying to Logging in......" );


        rsp  = conn.Get( POST_URI_LOGIN );
		conn.addBasicAuthorization("FC Server", m_username, m_password );
		
        
        /*while ( rsp.getInputStream().read( data ) != -1 )
        {
        	log( new String( data ) );
        }*/
                
        log( "Done." );
        return conn;
    }

    private HTTPResponse requestWipStatusReport( HTTPConnection conn) throws Exception
    {
        byte[] data         = new byte[1024];
        HTTPResponse   rsp  = null;

        System.out.println( "\nSubmitting the request for Wip Report......" );
        log( "Submitting the request for  Wip Report......" );
        
       NVPair params[] = new NVPair[ 7 ];
		params[0]		= new NVPair("VU81QUIwU0M6OTA0bXIycGs", "108562");
        rsp = conn.Get("/fc_server/fc_wip_rpt.php3", params );
        
        /*while ( rsp.getInputStream().read( data ) != -1 )
        {
            log( new String( data ) );
        }*/

        return rsp;
    }

    private void log( String message )
    {
        if ( message == null ) return;

        if ( m_adaptorLogger != null )
        {
            synchronized ( m_adaptorLogger )
            {
                m_adaptorLogger.logDebug( message + LINE_SEPARATOR );
            }
        }
        else
        {
            System.out.println( message );
        }
    }
}
